package com.homedo.microservice.open.service.gateway.manager.web.support;

import com.homedo.common.bean.data.ResponseData;
import com.homedo.common.bean.data.enums.ResponseEnum;
import com.homedo.common.exception.base.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Component
@ControllerAdvice
public class RestExceptionHandler {

    private final static Logger _LOGGER = LoggerFactory.getLogger(RestExceptionHandler.class);

    /**
     * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseData exceptionGet(Exception ex) {
        ResponseData responseData = new ResponseData();

        if (ex instanceof BaseException && ((BaseException) ex).getResponse() != null) {
            responseData.setResponseEnum(((BaseException) ex).getResponse());
            return responseData;
        }
        _LOGGER.error("[统一处理异常:{}]", ex.getMessage(), ex);
        responseData.setResponseEnum(ResponseEnum.UNKNOWN);
        responseData.setRespDesc(ex.getMessage());


//        if (ex instanceof UserContextException) {
//            responseData.setResponseEnum(ResponseEnum.NOT_LOGIN);
//        } else {
//            _LOGGER.error("[统一处理异常:{}]", ex.getMessage(), ex);
//            responseData.setResponseEnum(ResponseEnum.UNKNOWN);
//            responseData.setRespDesc(ex.getMessage());
//        }

        return responseData;
    }
}
